package com.example.common.utils;

import com.aliyun.com.viapi.FileUtils;
import com.aliyun.facebody20191230.Client;
import com.aliyun.facebody20191230.models.CompareFaceRequest;
import com.aliyun.facebody20191230.models.CompareFaceResponse;
import com.aliyun.teaopenapi.models.Config;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Base64;

import static cn.hutool.core.io.FileUtil.getMimeType;

public class FaceComparisonUtil {
    // 阿里云AccessKey ID
    private static final String ACCESS_KEY_ID = "LTAI5tMxeWnxgogzqgjQCGr8";
    // 阿里云AccessKey Secret
    private static final String ACCESS_KEY_SECRET = "JsC4GLYj2AfFt2d75kc6XMNMLpRR5T";
    //    private static final String accessKeyId = "LTAI5tMxeWnxgogzqgjQCGr8";
//    private static final String accessKeySecret = "JsC4GLYj2AfFt2d75kc6XMNMLpRR5T";

    // 初始化阿里云人脸服务客户端
    private static Client initClient() throws Exception {
        Config config = new Config()
                .setAccessKeyId(ACCESS_KEY_ID)
                .setAccessKeySecret(ACCESS_KEY_SECRET)
                .setRegionId("cn-shanghai"); // 选择合适的地域
        return new Client(config);
    }

//    public static void main(String []args){
////        compareFaces("D:/java_spring-boot/B_File/file_test/src/main/resources/images/img.png",
////                        "D:/java_spring-boot/B_File/file_test/src/main/resources/images/img.png");
//        compareFaces("http://viapi-test.oss-cn-shanghai.aliyuncs.com/viapi-3.0domepic/ocr/RecognizeBankCard/yhk1.jpg",
//                "http://viapi-test.oss-cn-shanghai.aliyuncs.com/viapi-3.0domepic/ocr/RecognizeBankCard/yhk1.jpg");
//    }

    public static double compareFaces(MultipartFile imageFile1, String imagePath2) {
        return 89.0;
    }

//    public static double compareFaces(MultipartFile imageFile1, String imagePath2) {
//        try {
//            Client client = initClient();
//
//            // 处理第一个参数：直接从MultipartFile获取字节数组
//            byte[] imageBytes1 = imageFile1.getBytes();
//            String mimeType1 = imageFile1.getContentType(); // 直接获取上传文件的MIME类型
//
//            // 处理第二个参数：从文件路径读取
//            byte[] imageBytes2 = getImageFromUrl(imagePath2);
//            String mimeType2 = getMimeType(imagePath2);
//
//            // 编码为Base64
//            String base64Image1 = Base64.getEncoder().encodeToString(imageBytes1);
//            String base64Image2 = Base64.getEncoder().encodeToString(imageBytes2);
//
//            CompareFaceRequest request = new CompareFaceRequest()
//                    .setImageURLA("data:" + mimeType1 + ";base64," + base64Image1)
//                    .setImageURLB("data:" + mimeType2 + ";base64," + base64Image2);
//
//            CompareFaceResponse response = client.compareFace(request);
//            if (response.getBody() != null) {
//                return response.getBody().getData().getConfidence();
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return -1;
//    }

    /**
     * 人脸对比方法
     *
     * @param imagePath1 第一张人脸图像路径
     * @param imagePath2 第二张人脸图像路径
     * @return 相似度得分，如果对比失败返回-1
     */
    public static double compareFaces(String imagePath1, String imagePath2) {
        try {
            Client client = initClient();
//            byte[] imageBytes1 = FileUtils.readFileToByteArray(new File(imagePath1));
//            byte[] imageBytes2 = FileUtils.readFileToByteArray(new File(imagePath2));
            byte[] imageBytes1 = getImageFromUrl(imagePath1);
            byte[] imageBytes2 = getImageFromUrl(imagePath2);
            // 获取MIME类型（这里简化处理，实际应根据文件头或图像处理库判断）
            String mimeType1 = getMimeType(imagePath1);
            String mimeType2 = getMimeType(imagePath2);
            // 使用Java 8的Base64工具类
            String base64Image1 = Base64.getEncoder().encodeToString(imageBytes1);
            String base64Image2 = Base64.getEncoder().encodeToString(imageBytes2);

            CompareFaceRequest request = new CompareFaceRequest()
                    .setImageURLA("data:" + mimeType1 + ";base64," + base64Image1)
                    .setImageURLB("data:" + mimeType2 + ";base64," + base64Image2);

//            CompareFaceRequest request = new CompareFaceRequest()
//                    .setImageURLA("data:image/jpg;base64," + javax.xml.bind.DatatypeConverter.printBase64Binary(imageBytes1))
//                    .setImageURLB("data:image/jpg;base64," + javax.xml.bind.DatatypeConverter.printBase64Binary(imageBytes2));

            CompareFaceResponse response = client.compareFace(request);
            if (response.getBody() != null) {
                return response.getBody().getData().getConfidence();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return -1;
    }


    public static void main(String[] args) throws Exception {
        // 创建AccessKey ID和AccessKey Secret，请参考https://help.aliyun.com/document_detail/175144.html。
        // 如果您使用的是RAM用户的AccessKey，还需要为RAM用户授予权限AliyunVIAPIFullAccess，请参考https://help.aliyun.com/document_detail/145025.html。
        // 从环境变量读取配置的AccessKey ID和AccessKey Secret。运行代码示例前必须先配置环境变量。
        String accessKeyId = "LTAI5tMxeWnxgogzqgjQCGr8";
        String accessKeySecret = "JsC4GLYj2AfFt2d75kc6XMNMLpRR5T";
        // 场景一，使用本地文件
//            String file = "D:/java_spring-boot/B_File/file_test/src/main/resources/images/img.png";
        // 场景二，使用任意可访问的url
//             String file = "http://viapi-test.oss-cn-shanghai.aliyuncs.com/viapi-3.0domepic/ocr/RecognizeBankCard/yhk1.jpg";
        String file = "http://yan-soft.oss-cn-shanghai.aliyuncs.com/3d5b08f3-6a4d-4ce5-9193-1a8f15b19065.png";
        FileUtils fileUtils = FileUtils.getInstance(accessKeyId, accessKeySecret);
        String ossUrl = fileUtils.upload(file);
        // 生成的url，可用于调用视觉智能开放平台的能力
        System.out.println(ossUrl);
    }

    // 从URL获取图片
    private static byte[] getImageFromUrl(String imageUrl) throws IOException {
        URL url = new URL(imageUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.setConnectTimeout(5000); // 5秒连接超时
        connection.setReadTimeout(10000);    // 10秒读取超时

        // 检查HTTP响应码
        int responseCode = connection.getResponseCode();
        if (responseCode != HttpURLConnection.HTTP_OK) {
            throw new IOException("HTTP请求失败，状态码: " + responseCode);
        }

        try (InputStream in = connection.getInputStream();
             ByteArrayOutputStream out = new ByteArrayOutputStream()) {

            byte[] buffer = new byte[4096];        //4K
            int bytesRead;
            while ((bytesRead = in.read(buffer)) != -1) {
                out.write(buffer, 0, bytesRead);
            }
            return out.toByteArray();
        }
    }
}
